<?php

namespace App\Http\ControllersVer1;

use Illuminate\Http\Request;

use Qiniu\Auth as QiniuAuth;
use Qiniu\Storage\UploadManager;

use Uuid;

use App\User;
use App\Avatar;
use App\Appointment;
use App\Book;


class UserController extends Controller
{
    /**
     * Create a new controller instance.
     *
     * @return void
     */
    public function __construct()
    {
        //
    }

    /**
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function refreshMyInfo(Request $request) {

        $me = $request->user();

        //todo: ???
        $levels_count = 1;
        $stones_count = 16;

        return response()->json([
            'code' => 2000,
            'me' => $me,
            'levels_count' => $levels_count,
            'stones_count' => $stones_count,
            'msg' => 'success'
        ]);
    }


    public function updateMyInfo(Request $request) {

        $this->validate($request, [
            'nickname' => 'max:32',
            'location' => 'max:32',
            'intro' => 'max:300',
            'gender' => 'max:1',
            'motto' => 'max:32',
            'school' => 'max:32',
            'job' => 'max:32'
        ]);

        $me = $request->user();

        if($request->has('nickname')) {
            //$nickname = $request->input('nickname');
            $nickname = str_replace(' ', '-', $request->input('nickname'));


            $user_same_nickname = User::where('nickname', $nickname)->first();

            if (is_null($user_same_nickname)) {
                $me->nickname = $nickname;

            } else {
                return response()->json([
                    'code' => 4060,
                    'msg' => $nickname.'该昵称已被使用,那就换一个吧!'
                ]);
            }
        }

        if($request->has('location')) {
            $me->location = $request->input('location');
        }

        if($request->has('intro')) {
            $me->intro = $request->input('intro');
        }

        if($request->has('motto')) {
            $me->motto = $request->input('motto');
        }

        if($request->has('gender')) {
            $me->gender = $request->input('gender');

            //todo: del the old gender geo data in redis

        }

        if($request->has('school')) {
            $me->school = $request->input('school');
        }

        if($request->has('job')) {
            $me->job = $request->input('job');
        }

        $me->save();
        //$me = User::find($me->id);

        return response()->json([
            'code' => 2000,
            'me' => $me,
            'msg' => 'success'
        ]);


    }



    /**
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     * @throws \Exception
     */
    public function updateMyAvatar(Request $request) {


        $this->validate($request, [
            'image' => 'mimes:jpeg,png'
        ]);


        //
        if (!$request->hasFile('image')) {
            //
            return response()->json([
                'code' => 4060,
                'msg' => 'no photo file'
            ]);
        }

        //
        if (!$request->file('image')->isValid()) {
            //
            return response()->json([
                'code' => 4060,
                'msg' => 'photo upload is not valid.'
            ]);
        }

        //
        //$ext = $request->file('image')->getClientOriginalExtension();

        $access_key = 'D5r1vUBg8Xc5UjdVYorZRdHMpvaONPrgxcyyqHxn';
        $secret_key = 'A5c7sTC7nooJCJ8YV-HOmoJFO0Wu1JuLudcWtMvF';

        $auth = new QiniuAuth($access_key, $secret_key);
        $bucket = 'xreacting';
        $upload_token = $auth->uploadToken($bucket);

        // 要上传文件的本地路径
        $file_path = $request->file('image');


        // 上传到七牛后保存的文件名
        //todo: uuid for image
        $key = str_replace('-', '', Uuid::generate(4)->string);

        // 初始化 UploadManager 对象并进行文件的上传
        $upload_mgr = new UploadManager();

        // 调用 UploadManager 的 putFile 方法进行文件的上传
        list($upload_ret, $upload_err) = $upload_mgr->putFile($upload_token, $key, $file_path);

        if (is_null($upload_ret)) {

            return response()->json([
                'code' => 4060,
                'msg' => 'upload image failed.'
            ]);
        }

        if ($upload_ret['key'] != $key) {

            return response()->json([
                'code' => 4060,
                'msg' => 'upload_ret key is wrong'
            ]);
        }

        $me = $request->user();

        //Avatar::where('user_id', $me->id)->delete();
        $avatar = new Avatar;
        $avatar->user_id = $me->id;
        $avatar->uuid = $key;
        $avatar->cloud = 'Qiniu';
        $avatar->bucket = $bucket;
        $avatar->save();

        //$me = User::find($me->id);
        //todo: ????
        $avatar_url = 'http://7xohc2.com1.z0.glb.clouddn.com/'.$avatar->uuid;

        return response()->json([
            'code' => 2000,
            //'me' => $me,
            'avatar_url' => $avatar_url,
            'msg' => 'success.'
        ]);
    }


    //-------------My Appointments

    /**
     * @param Request $request
     */
    public function showMyReceivedAppointments(Request $request) {

        $me = $request->user();

        $count = 50;

        $appointments = Appointment::where('predecessor_id', $me->id)
            ->whereIn('status', ['os', 'ap'])
            ->orderBy('id', 'desc')
            ->take($count)
            ->get();

        return response()->json([
            'code' => 2000,
            'appointments' => $appointments,
            'msg' => 'success!'
        ]);

    }

    /**
     * @param Request $request
     */
    public function showMySentAppointments(Request $request) {

        $me = $request->user();

        $count = 50;

        $appointments = Appointment::where('successor_id', $me->id)
            ->whereIn('status', ['os', 'ap'])
            ->orderBy('id', 'desc')
            ->take($count)
            ->get();

        return response()->json([
            'code' => 2000,
            'appointments' => $appointments,
            'msg' => 'success!'
        ]);

    }




    //------------ user
    /**
     * @param Request $request
     * @param $user_uuid
     * @return \Illuminate\Http\JsonResponse
     */
    public function showUser(Request $request, $user_uuid) {

        if (strlen($user_uuid) != 32) {
            return response()->json([
                'code' => 4060,
                'msg' => 'wrong user uuid!'
            ]);
        }

        $user = User::where('uuid', $user_uuid)->first();

        if (is_null($user)) {
            return response()->json([
                'code' => 4060,
                'msg' => 'no user!'
            ]);
        }

        $count = 10;

        $books_hold = Book::where('holder_id', $user->id)
            ->where("status", "1")
            ->orderBy('id', 'desc')
            ->take($count)
            ->get();

        $books_handed  = [];

        $books_gave = Book::where('giver_id', $user->id)
            ->where("status", "1")
            ->orderBy('id', 'desc')
            ->take($count)
            ->get();

        return response()->json([
            'code' => 2000,
            'user' => $user,
            'books_hold' => $books_hold,
            'books_handed' => $books_handed,
            'books_gave' => $books_gave,
            'msg' => 'success!'
        ]);

    }

}
